/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aiaudio.processing.reduce.klsh.kmeaning.mappers;

import aiaudio.Application;
import aiaudio.database.tablegroup.InitialDataTableGroup;
import aiaudio.database.tables.DataMetricsTable;
import java.io.IOException;
import java.util.Random;
import java.util.Vector;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.io.IntWritable;

/**
 *
 * @author nastya
 */
public class KMeansTestSetMapper extends TableMapper<ImmutableBytesWritable, IntWritable> {

    public static final int DEFAULT_TEST_SET_SIZE = 100;
    public static final String PARAM_TEST_SET_SIZE = "testSetSize";
    private int testSetSize;
    private Vector<Long> indices = new Vector<Long>();

    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        super.setup(context);
        testSetSize = context.getConfiguration().getInt(PARAM_TEST_SET_SIZE, DEFAULT_TEST_SET_SIZE);
        collectIndices();
    }

    private void collectIndices() throws IOException {
        HTable dataMetricsTable = Application.database().getByName(InitialDataTableGroup.getInstance().getDataMetricsTable()).getTable();
        long artistsCount = DataMetricsTable.getArtistsCount(dataMetricsTable);

        Random r = new Random();
        long nextIndex;
        while (indices.size() < testSetSize) {
            nextIndex = (long) (r.nextDouble() * artistsCount);
            if (!indices.contains(nextIndex)) {
                indices.add(nextIndex);
            }
        }
    }
    long currentIndex = 0;

    @Override
    protected void map(ImmutableBytesWritable key, Result value, Context context) throws IOException, InterruptedException {
        if (indices.contains(currentIndex)) {
            context.write(new ImmutableBytesWritable(key), new IntWritable(0));
        }
        currentIndex++;
    }
}
